﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using vwsol_DuHoc.Areas.Administrator.Models;
using System.IO;

namespace vwsol_DuHoc.Areas.Administrator.Controllers
{
    public class AdminCourseController : Controller
    {
        //
        // GET: /Administrator/AdminCourse/

        public ActionResult Index(string message = "", string level = "")
        {
            try
            {
                if (level == "Success")
                {
                    ViewBag.Success = message;
                }
                if (level == "Warning")
                {
                    ViewBag.Warning = message;
                }
                if (level == "Error")
                {
                    ViewBag.Error = message;
                }
                using (AdminVwsolDbDataContext db = new AdminVwsolDbDataContext())
                {
                    List<Course> model = new List<Course>();
                    model = db.Courses.Where(m=>m.IsDelete == false).OrderByDescending(i=>i.CreateDate).ToList();
                    return View(model);
                }
            }
            catch (Exception)
            {
                ViewBag.Error = "Lỗi lấy dữ liệu khóa học!";
                List<Course> model = new List<Course>();
                return View(model);
            }
        }

        public ActionResult CreateCourse()
        {
            using (AdminVwsolDbDataContext db = new AdminVwsolDbDataContext())
            {
                Course model = new Course();
                return View(model);
            }
        }

        [HttpPost]
        public ActionResult CreateCourse(Course model, HttpPostedFileBase file)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    ViewBag.Warning = "Dữ liệu khóa học không đúng!";
                    return View();
                }
                using (AdminVwsolDbDataContext db = new AdminVwsolDbDataContext())
                {
                    /*hình ảnh*/
                    if (!(file == null || file.ContentLength == 0))
                    {
                        string extension = Path.GetExtension(file.FileName);
                        extension = extension.ToLower();
                        if (!(extension == ".jpg" || extension == ".gif" || extension == ".png"))
                        {
                            ViewBag.Warning = "Hình ảnh không đúng định dạng!";
                            return View(model);
                        }
                        string physicalPath = Server.MapPath(Url.Content("~/Resource/img"));
                        string fileName = String.Format("{0}" + extension, Guid.NewGuid().ToString());
                        string imagePath = Path.Combine(physicalPath, fileName);
                        file.SaveAs(imagePath);
                        model.Image = "~/Resource/img/" + fileName;
                    }
                    /*end*/
                    model.Default();
                    db.GetTable(typeof(Course)).InsertOnSubmit(model);
                    db.SubmitChanges();
                    return RedirectToAction("Index", new { message = "Thêm khóa học thành công!", level = "Success" });
                }
            }
            catch (Exception)
            {
                ViewBag.Error = "Lỗi tạo khóa học!";
                return View(model);
            }
        }

        public ActionResult EditCourse(int id)
        {
            try
            {
                using (AdminVwsolDbDataContext db = new AdminVwsolDbDataContext())
                {
                    Course model = db.Courses.Where(m => m.CourseID == id).SingleOrDefault();
                    return View(model);
                }
            }
            catch (Exception)
            {
                return RedirectToAction("Index", new { message = "Lỗi edit khóa học!", level = "Error" });
            }
        }

        [HttpPost]
        public ActionResult EditCourse(Course model, HttpPostedFileBase file)
        {
            Course updateModel = new Course();
            try
            {
                using (AdminVwsolDbDataContext db = new AdminVwsolDbDataContext())
                {
                    updateModel = db.Courses.Where(m => m.CourseID == model.CourseID).SingleOrDefault();
                    updateModel.CourseName = model.CourseName;
                    updateModel.CourseDescription = model.CourseDescription;
                    updateModel.CourseTag = model.CourseTag;
                    updateModel.CourseContent = model.CourseContent == null? "" : model.CourseContent;
                    /*hình ảnh*/
                    if (!(file == null || file.ContentLength == 0))
                    {
                        string extension = Path.GetExtension(file.FileName);
                        extension = extension.ToLower();
                        if (!(extension == ".jpg" || extension == ".gif" || extension == ".png"))
                        {
                            ViewBag.Warning = "Hình ảnh không đúng định dạng!";
                            return View(updateModel);
                        }
                        string physicalPath = Server.MapPath(Url.Content("~/Resource/img"));
                        string fileName = String.Format("{0}" + extension, Guid.NewGuid().ToString());
                        string imagePath = Path.Combine(physicalPath, fileName);
                        file.SaveAs(imagePath);
                        model.Image = "~/Resource/img/" + fileName;
                    }
                    /*end*/
                    updateModel.Image = model.Image;
                    db.SubmitChanges();
                    ViewBag.Success = "Cập nhật khóa học thành công!";
                    return View(updateModel);
                }
            }
            catch (Exception)
            {
                ViewBag.Error = "Lỗi edit khóa học!";
                return View(updateModel);
            }
        }

        [HttpPost]
        public ActionResult DeleteCourse(FormCollection form)
        {
            try
            {
                int CourseID = Convert.ToInt32(form["id"]);
                using (AdminVwsolDbDataContext db = new AdminVwsolDbDataContext())
                {
                    Course model = db.Courses.Where(m => m.CourseID == CourseID).SingleOrDefault();
                    model.IsDelete = true;
                    db.SubmitChanges();
                    return RedirectToAction("Index", new { message = "Xoá khóa học thành công!", level = "Success" });
                }
            }
            catch (Exception)
            {
                return RedirectToAction("Index", new { message = "Lỗi xóa khóa học!", level = "Error" });
            }
        }
    }
}
